package com.example.controller;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.Result;
import com.example.entity.Account;
import com.example.entity.ClassInfo;
import com.example.entity.TeacherInfo;
import com.example.entity.XuankeInfo;
import com.example.exception.CustomException;
import com.example.service.ClassInfoService;
import com.example.service.XuankeInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 涛某
 * @version 1.0
 * @date 2024/3/27 9:33
 */
@RequestMapping("/classInfo")
@RestController
public class ClassInfoController {
    @Autowired
    private ClassInfoService classInfoService;
    @Autowired
    private XuankeInfoService xuankeInfoService;


    @GetMapping()
    public Result findAll(){
       List<ClassInfo> list =  classInfoService.findAll();

        return Result.success(list);
    }
    @PostMapping()
    public Result add(@RequestParam ClassInfo classInfo){
        classInfoService.add(classInfo);
        return Result.success();
    }
    @PutMapping
    public Result update(@RequestParam ClassInfo classInfo){
        classInfoService.update(classInfo);
        return Result.success();
    }
    @DeleteMapping("{id}")
    public Result del(@PathVariable Long id){
        classInfoService.del(id);
        return Result.success();
    }
    @GetMapping("{search}")
    public Result findsearch(@PathVariable(name = "search") String search){
        List<ClassInfo> list =  classInfoService.findsearch(search);
        return Result.success(list);
    }
    @PostMapping("/xuanke")
    public Result xuanke(@RequestBody ClassInfo classInfo , HttpServletRequest request){

     /*   //先判断已选人数和开班人数相等不相等
        if (classInfo.getKaiban().equals(classInfo.getYixuan())){
            throw new CustomException("-1","选课人数已经满");
        }*/

        Account user  = (Account) request.getSession().getAttribute("user");
        if (ObjectUtil.isEmpty(user)){
            throw new CustomException("-1","登录已经失效，请重新登录");

        }
        //将选课信息表里的字段补全
        XuankeInfo xuankeInfo = new XuankeInfo();
        BeanUtils.copyProperties(classInfo,xuankeInfo);
        xuankeInfo.setId(null);

        xuankeInfo.setStudentid(user.getId());
        xuankeInfo.setStatus("等待开课");
        xuankeInfoService.add(xuankeInfo);
        //将选课信息里的已选加1
        classInfo.setYixuan(classInfo.getYixuan() + 1);
        classInfoService.update(classInfo);






        return Result.success();










    }

}
